import { useCallback, useEffect, useRef, useState } from 'react';
import Taro, { useLoad, useUnload } from '@tarojs/taro';
import { AtSearchBar } from 'taro-ui';
import { View, Text, Image, ScrollView, Input } from '@tarojs/components';
import './index.scss';
import FooterBarComponent from '@/components/footerBar';
import apiRequest from '@/service/apiRequest';

import "taro-ui/dist/style/components/search-bar.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/icon.scss";
import { debounce } from '@/utils/common';

function PetCategoryPage() {
    // 宠物分类数据
    const [categories, setCategories] = useState([]);

    // 热门宠物品种
    const [popularBreeds, setPopularBreeds] = useState([]);

    const [searchVal, setSearchVal] = useState("");
    const [searchResultVal, setSearchResultVal] = useState<any>(null);
    const searchFnRef = useRef<any>(null);

    // 导航到分类详情页
    const navigateToCategory = (id, categoryName) => {
        Taro.navigateTo({
            url: `/petEncyclopedia/pages/category/index?categoryId=${id}&categoryName=${categoryName}`
        });
    };

    // 导航到品种详情页
    const navigateToBreed = (breed) => {
        Taro.navigateTo({
            url: `/petEncyclopedia/pages/detail/index?petVarietyId=${breed.id}`
        });
    };

    const requestCategories = async () => {
        let result = await apiRequest.get("/api/pet_encyclopedias/categories", {tradeType: 1});
        if (result) {
            setCategories(result);
        }
    }
    
    const requestPopularBreeds = async () => {
        let result = await apiRequest.get("/api/pet_encyclopedias/hot");
        if (result) {
            setPopularBreeds(result);
        }
    }

    const handleSearchChange = (value) => {
        console.log("value", value);
        setSearchVal(value);
    }

    // 在useEffect中创建防抖函数
    useEffect(() => {
        // 创建防抖函数
        searchFnRef.current = debounce((value) => {
            console.log("请求入参数", value);
            
            apiRequest.get("/api/pet_encyclopedias/search", {keyword: value}).then((result) => {
                if (result) {
                setSearchResultVal(result);
                }
            });
        }, 800);
        
        // 组件卸载时取消防抖
        return () => {
            if (searchFnRef.current && searchFnRef.current.cancel) {
                searchFnRef.current.cancel();
            }
        };
    }, []); // 只在组件挂载时创建一次
    
    // 监听searchVal变化并调用防抖函数
    useEffect(() => {
        if (searchVal && searchFnRef.current) {
            searchFnRef.current(searchVal);
        } else {
            setSearchResultVal(null);
            // 这里一定要取消，不然搜索框数据清除后还是会调用一次防抖函数
            if (searchFnRef.current && searchFnRef.current.cancel) {
                searchFnRef.current.cancel();
            }
        }
    }, [searchVal]); // 从依赖中移除debouncedSearch

    const handleClickSearchItem = (breed) => {
        Taro.navigateTo({
            url: `/petEncyclopedia/pages/detail/index?petVarietyId=${breed.id}`
        });
    }

    useLoad(() => {
        requestCategories();
        requestPopularBreeds();
    })

    useUnload(() => {
    })

    return (
        <View className={searchResultVal ? 'pet-category-container disabled' : 'pet-category-container'}>
            {/* 搜索框 */}
            <View className='search-box'>
                <AtSearchBar
                    value={searchVal}
                    onChange={handleSearchChange}
                    placeholder='搜索宠物品种'
                    maxLength={20}
                    fixed={true}
                />
                {
                    searchResultVal ?
                    (
                        <View className='search-result-popup'>
                            <View className='search-result-box'>
                                {
                                    searchResultVal.length > 0 ?
                                    searchResultVal.map((breed: any) => (
                                        <View
                                            className='search-item'
                                            key={breed.id}
                                            onClick={() => handleClickSearchItem(breed)}
                                        >
                                            { breed.varietyName }
                                        </View>
                                    )) : (
                                        <View className='search-empty'>
                                            <Text>没有找到相关宠物品种</Text>
                                        </View>
                                    )
                                }
                            </View>
                        </View>
                    ) : null
                }
            </View>

            {/* 分类列表 */}
            <View className='section-title'>
                <Text className='title'>宠物分类</Text>
            </View>

            <View className='category-grid'>
                {categories.map((category: any) => (
                    <View
                        key={category.id}
                        className='category-item'
                        onClick={() => navigateToCategory(category.id, category.cateName)}
                    >
                        <Image className='category-image' src={category.imgUrl} mode='aspectFill' />
                        <View className='category-info'>
                            <Text className='category-name'>{category.cateName}</Text>
                            {
                                category.varietyCount ? (
                                    <Text className='category-count'>{category.varietyCount}个品种</Text>
                                ) : null
                            }
                        </View>
                    </View>
                ))}
            </View>

            {/* 热门品种 */}
            <View className='section-title'>
                <Text className='title'>热门宠物品种</Text>
            </View>

            <ScrollView className='breeds-scroll' scrollX>
                <View className='breeds-container'>
                    {popularBreeds.map((breed: any) => (
                        <View
                            key={breed.id}
                            className='breed-item'
                            onClick={() => navigateToBreed(breed)}
                        >
                            <Image className='breed-image' src={breed.varietyImage} mode='aspectFill' />
                            <Text className='breed-name ellipsis'>{breed.varietyName}</Text>
                            <Text className='breed-category'>{breed.petCategoryName}</Text>
                        </View>
                    ))}
                </View>
            </ScrollView>

            {/* 宠物百科 */}
            {/* <View className='section-title'>
                <Text className='title'>宠物百科</Text>
                <Text className='more'>查看全部</Text>
            </View> */}

            {/* <View className='wiki-list'>
                <View className='wiki-item'>
                    <Image className='wiki-image' src='https://images.unsplash.com/photo-1548767797-d8c844163c4c' mode='aspectFill' />
                    <View className='wiki-content'>
                        <Text className='wiki-title'>如何选择适合自己的宠物</Text>
                        <Text className='wiki-desc'>根据生活环境、时间和经济条件选择合适的宠物伙伴</Text>
                        <Text className='wiki-tag'>新手指南</Text>
                    </View>
                </View>

                <View className='wiki-item'>
                    <Image className='wiki-image' src='https://images.unsplash.com/photo-1583337130417-3346a1be7dee' mode='aspectFill' />
                    <View className='wiki-content'>
                        <Text className='wiki-title'>宠物常见疾病预防指南</Text>
                        <Text className='wiki-desc'>了解如何预防宠物常见疾病，保持宠物健康</Text>
                        <Text className='wiki-tag'>健康护理</Text>
                    </View>
                </View>
            </View> */}

            {/* 底部 */}
            <FooterBarComponent footerBarIndex={2} />
        </View>
    );
}

export default PetCategoryPage;